package com.example.music.adapter;

import android.graphics.Color;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.music.R;
import com.example.music.model.Song;

import java.util.List;

public class PlaylistAdapter extends RecyclerView.Adapter<PlaylistAdapter.ViewHolder> {

    private List<Song> songList;
    private int currentPosition = -1;

    public static interface OnItemClickListener {
        void onItemClick(int position);
    }

    private final OnItemClickListener listener;

    public PlaylistAdapter(List<Song> songList, OnItemClickListener listener) {
        this.songList = songList;
        this.listener = listener;
    }

    public void setCurrentPosition(int newPosition) {
        if (newPosition == currentPosition) return;

        int oldPosition = currentPosition;
        currentPosition = newPosition;

        if (oldPosition >= 0 && oldPosition < getItemCount()) {
            notifyItemChanged(oldPosition);
        }

        if (newPosition >= 0 && newPosition < getItemCount()) {
            notifyItemChanged(newPosition);
        }
    }


    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_playlist_song, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Song song = songList.get(position);
        String displayText = song.getTitle() + " - " + song.getArtist();
        holder.textView.setText(displayText);

        // 设置高亮样式
        if (position == currentPosition) {
            holder.textView.setTypeface(null, Typeface.BOLD);
            holder.container.setBackgroundColor(Color.parseColor("#E0F7FA")); // 浅蓝色
        } else {
            holder.textView.setTypeface(null, Typeface.NORMAL);
            holder.container.setBackgroundColor(Color.TRANSPARENT);
        }

        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return songList.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView textView;
        LinearLayout container;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.tv_playlist_song);
            container = itemView.findViewById(R.id.item_container);
        }
    }
}